package com.kewu.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author wangning
 * @create 2024-05-29-14:54
 */
public class CronUtil {
    public final static String YYYY_MM_DD = "yyyy-MM-dd hh:mm:ss";

    public static String toCronExpression(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        return new StringBuffer().append(second).append(" ").append(minute).append(" ").append(hour)
                .append(" ").append(day).append(" ").append(month).append(" ").append("?").append(" ").append(year).toString();
    }

    public static String toCronExpression(String dateString) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        Date date = format.parse(dateString);
        return toCronExpression(date);
    }
}